// kucunLocal.js 库存本地存储操作工具，包含库存信息的增删查改等方法
const RECORD_KEY = 'kucunRecords';

// 获取所有入库/出库记录
export function getRecordList() {
  const list = JSON.parse(localStorage.getItem(RECORD_KEY) || '[]');
  // 按时间倒序
  return list.sort((a, b) => b.time - a.time);
}

// 新增一条入库/出库记录，并自动更新库存
export function addRecord(item) {
  const list = getRecordList();
  const now = Date.now();
  const record = { ...item, time: now, timeStr: new Date(now).toLocaleString() };
  list.push(record);
  localStorage.setItem(RECORD_KEY, JSON.stringify(list));
}

// 获取当前库存统计
export function getStockList() {
  const records = getRecordList();
  const stockMap = {};
  records.forEach(r => {
    if (!stockMap[r.name]) {
      stockMap[r.name] = { name: r.name, stock: 0, unit: r.unit, remark: r.remark };
    }
    if (r.type === 'in') {
      stockMap[r.name].stock += Number(r.num);
    } else if (r.type === 'out') {
      stockMap[r.name].stock -= Number(r.num);
    }
    // 备注和单位以最新一次为准
    stockMap[r.name].unit = r.unit;
    stockMap[r.name].remark = r.remark;
  });
  // 只展示有库存的物品
  return Object.values(stockMap).filter(i => i.stock > 0);
} 